/**
 * FileName: UserController
 * Author:   Administrator
 * Date:     2018/11/16 16:42
 * Description: 后台用户管理
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.fortune.rainshinesystem.controller;

import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.entity.LoginRecordEntity;
import com.fortune.rainshinecommon.model.LoginDtoModel;
import com.fortune.rainshinecommon.model.LoginParamsModel;
import com.fortune.rainshinecommon.model.SysUsers;
import com.fortune.rainshinecommon.model.system.Authorities;
import com.fortune.rainshinecommon.model.system.LoginRecord;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.query.UserIdQuery;
import com.fortune.rainshinecommon.query.UserQuery;
import com.fortune.rainshinecommon.util.TokenUtils;
import com.fortune.rainshinecommon.util.UserAgentGetter;
import com.fortune.rainshinesystem.mapper.AuthoritiesMapper;
import com.fortune.rainshinesystem.mapper.SysUserRoleMapper;
import com.fortune.rainshinesystem.mapper.SysUsersMapper;
import com.fortune.rainshinesystem.mapper.UserRoleMapper;
import com.fortune.rainshinesystem.service.LoginRecordService;
import com.fortune.rainshinesystem.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 〈一句话功能简述〉<br>
 * 〈后台用户管理〉
 *
 * @author Administrator
 * @create 2018/11/16
 * @since 1.0.0
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService service;
    @Autowired
    private SysUsersMapper mapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private AuthoritiesMapper authoritiesMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private LoginRecordService loginRecordService;


    /* 添加用户 */
    @PostMapping("/add")
    public MsgModel add(@RequestBody User user) {
        return service.addUser(user);
    }

    /* 获取用户列表 */
    @PostMapping("/list")
    public MsgModel list(@RequestBody SysUsers user) {
        return service.list();
    }

    /* 获取用户 */
    @PostMapping("/getUserInfo")
    public User getUserInfoByAccount(@RequestBody String account) {
        User user = new User();
        user.setUsername(account);
        try {
            user = mapper.selectOne(user);
        } catch (Exception e) {
            logger.error("getUserInfo ====> {}", e);
        }
        return user;
    }

    // 验证码登录
    @PostMapping("/userSmsLogin")
    public LoginDtoModel userSmsLogin(@RequestBody LoginParamsModel loginParams) {
        LoginDtoModel appLoginDto = new LoginDtoModel();
        try {
            String account = loginParams.getUserAccount();
            User user = new User();
            user.setUsername(account);
            user = mapper.selectOne(user);

            //获取登录用户的角色
            Integer roleId = sysUserRoleMapper.selectRoleIdByUserId(user.getUserId());

            List<Authorities> authorities = authoritiesMapper.selectRoleAuthByRoleId(roleId);

            // 生成token
            String userToken = TokenUtils.getAcessToken(account);

            // 用户存在刷新token即返回
            if (user.getUserId() != null) {
                BeanUtils.copyProperties(userToken, appLoginDto);
                appLoginDto.setUserToken(userToken);
                appLoginDto.setUserId(user.getUserId());
                appLoginDto.setUserAccount(account);
                appLoginDto.setRoleId(roleId);
                appLoginDto.setAuthorities(authorities);
                appLoginDto.setNickName(user.getNickName());
                appLoginDto.setPicUrl(user.getAvatar());
                appLoginDto.setSex(user.getSex());
                appLoginDto.setPhone(user.getPhone());
                appLoginDto.setUserStatus(user.getState());
            }
        } catch (Exception e) {
            logger.error("userSmsLogin ====> {}", e);
        }
        return appLoginDto;
    }

    /**
     * 通过id获取user
     * @param id
     * @return
     */
    @PostMapping("/getUserById")
    public User getUserById(@RequestBody Integer id){
        return mapper.selectById(id);
    }

    /**
     * 获取门店的在职店员
     * @param shopId
     * @return
     */
    @PostMapping("/getShopAssistantsByShopId")
    public List<User> getShopAssistantsByShopId(@RequestBody Integer shopId){
        return service.getShopAssistantsByShopId(shopId, 0);
    }

    /**
     * 通过电话获取用户
     * @param phone
     * @return
     */
    @PostMapping("/getUsersByPhone")
    public List<User> getUsersByPhone(@RequestBody String phone){
        return service.getUsersByPhone(phone);
    }

    /**
     * 获取门店的所有店员（包括离职）
     * @param shopId
     * @return
     */
    @PostMapping("/getAllAssistantsByShopId")
    public List<User> getAllAssistantsByShopId(@RequestBody Integer shopId){
        return service.getShopAssistantsByShopId(shopId, null);
    }

    /**
     * 获取用户权限id
     * @param userId
     * @return
     */
    @PostMapping("/getRoleIdByUserId")
    public Integer getRoleIdByUserId(@RequestBody Integer userId){
        return userRoleMapper.getRoleIdByUserId(userId);
    }

    /**
     * 修改用户密码
     * @param query
     * @return
     */
    @PostMapping("/updatePsw")
    public MsgModel updatePsw(@RequestBody UserQuery query){
        return service.updatePsw(query);
    }

    /**
     * 修改用户头像
     * @param query
     * @return
     */
    @PostMapping("/updateAvatar")
    public MsgModel updateAvatar(@RequestBody UserQuery query){
        return service.updateAvatar(query);
    }

    /**
     * 获取所有招商人员列表
     * @param query
     * @return
     */
    @PostMapping("/getAllMerchants")
    public MsgModel getAllMerchants(@RequestBody UserIdQuery query){
        return service.getAllMerchants(query);
    }

    /**
     * 添加登录日志
     */
    @PostMapping("/addLoginRecord")
    public void addLoginRecord(@RequestBody LoginRecordEntity loginRecordEntity) {
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setUserId(loginRecordEntity.getUserId());
        loginRecord.setOsName(loginRecordEntity.getOsName());
        loginRecord.setDevice(loginRecordEntity.getDevice());
        loginRecordService.add(loginRecord);
    }
}